from odoo import models, fields, api, _
from odoo.exceptions import UserError

import logging


_logger = logging.getLogger(__name__)


class AccountMoveDuanhao(models.TransientModel):
    _name = "account.move.duan.hao"
    _description = "account move duan hao"

    def _default_ids(self):
        _logger.info('_default_ids')
        records = self.env['account.move'].browse(
            self._context.get('active_ids'))
        for record in records:
            record.custom_name = record.name
        return records

    account_move_ids = fields.Many2many('account.move',
                                        string="凭证号", required=True, default=_default_ids)

    prefix_name = fields.Char(string='前缀')
    number = fields.Integer(string='号码位数')
    code = fields.Integer(string='开始号码')

    do_text = fields.Char(string=' ')

    @api.onchange('prefix_name', 'number', 'code')
    def auto_change(self):
        if self.prefix_name and self.number != 0 and self.code != 0:
            self.do_text = '开始计算'
            account_move_ids = self.account_move_ids.sorted(
                key=lambda r: r.name)
            tem_code = self.code
            for account_move in account_move_ids:
                tem = str(tem_code).zfill(self.number)
                account_move.custom_name = self.prefix_name + tem
                _logger.info(account_move.custom_name)
                tem_code = tem_code + 1
            self.do_text = ' '

    # @api.one
    # def auto_change_name(self):
    #     account_move_ids = self.account_move_ids.sorted(key=lambda r: r.name)
    #     tem_code = self.code
    #     for account_move in account_move_ids:
    #         tem = str(tem_code).zfill(self.number)
    #         account_move.name = self.prefix_name + tem
    #         _logger.info(account_move.name)
    #         tem_code = tem_code + 1

    @api.multi
    def validate_move(self):
        for record in self:
            for account_move in record.account_move_ids:
                account_move.name = account_move.custom_name
        return {'type': 'ir.actions.act_window_close'}
